package com.hb.webflux.service;


import com.hb.webflux.entity.User;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserService {

    // 模拟数据库存储
    private Map<Integer, User> map = new HashMap<>();

    public UserService() {
        map.put(1, new User("zhangsan"));
        map.put(2, new User("lisi"));
        map.put(3, new User("wangwu"));
    }

    // 根据id查询
    public Mono<User> getById(Integer id) {
        System.out.println(111);
        Mono<User> userMono = Mono.justOrEmpty(map.get(id));;
        System.out.println(222);
        // 返回数据或空值
        return userMono;
    }

    public User sleepOneValue (Integer id) throws InterruptedException {
        Thread.sleep(2000);
        return map.get(id);
    }


    // 查询多个
    public Flux<User> getAll() throws InterruptedException {
        System.out.println(111);
        //Collection<User> values = this.sleepMoreValue();
        Flux<User> userFlux = Flux.fromIterable(this.sleepMoreValue());
        System.out.println(222);
        return userFlux;
    }

    public  Collection<User> sleepMoreValue () throws InterruptedException {
        Thread.sleep(2000);
        Collection<User> values = map.values();
        return values;
    }

    // 保存
    public Mono<Void> save(Mono<User> userMono) {
        return userMono.doOnNext(user -> {
            int id = map.size() + 1;
            map.put(id, user);
        }).thenEmpty(Mono.empty()); // 最后置空
    }
}

